package com.base.cn.platform.os.service.manage.group;

import com.base.cn.platform.os.common.mybatis.BaseBiz;
import com.base.cn.platform.os.common.utils.DataUtil;
import com.base.cn.platform.os.common.utils.ObjectUtils;
import com.base.cn.platform.os.common.utils.StringUtils;
import com.base.cn.platform.os.dao.manage.group.SysGroupDao;
import com.base.cn.platform.os.entity.manage.group.SysGroup;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 部门业务类
 *
 * @author s.li
 * @create 2018-02-05 16:34
 */
@Service
public class SysGroupBiz extends BaseBiz<SysGroup,SysGroupDao> {

    @Autowired
    private SysGroupFunctionBiz sysGroupFunctionBiz;

    /**
     * 保存部门信息
     * @param sysGroup 部门对象
     * @return SysGroup
     */
    @Transactional(rollbackFor =  IllegalArgumentException.class)
    public SysGroup saveSysGroup(SysGroup sysGroup){
        //修改
        if(DataUtil.idIsNotNull(sysGroup.getId())){
            SysGroup _sysGroup = this.findById(sysGroup.getId());
            _sysGroup.setGroupName(sysGroup.getGroupName());
            _sysGroup.setDepict(sysGroup.getDepict());
            this.updateById(_sysGroup,null);
            //保存部门的权限
            sysGroupFunctionBiz.saveGroupFunction(sysGroup.getId(),sysGroup.getFunctionIds());
            return _sysGroup;
        }else{//添加
            this.save(sysGroup);
            //保存部门的权限
            sysGroupFunctionBiz.saveGroupFunction(sysGroup.getId(),sysGroup.getFunctionIds());
        }
        return sysGroup;
    }

    /**
     * 查询部门列表，（分层）
     * @param sysGroup 查询条件
     * @return  List<SysGroup>
     */
    public List<SysGroup> findLayeredSysGroupList(SysGroup sysGroup){
        List<SysGroup> sysGroupList = this.findSysGroupList(sysGroup);
        if(ObjectUtils.isNotEmpty(sysGroupList)){
            sysGroupList = handleLayered(sysGroupList);
        }
        return sysGroupList;
    }

    /**
     * 查询部门列表
     * @param sysGroup 查询对象
     * @return List<SysGroup>
     */
    public List<SysGroup> findSysGroupList(SysGroup sysGroup){
        StringBuilder whereSql = new StringBuilder(" status!=3");
        if(ObjectUtils.isNotEmpty(sysGroup)){
            if(StringUtils.isNotEmpty(sysGroup.getGroupName())){
                whereSql .append(" and groupName like '%").append(sysGroup.getGroupName().trim()).append("%'");
            }
            if(ObjectUtils.isNotEmpty(sysGroup.getStatus()) && sysGroup.getStatus().intValue()>0){
                whereSql .append(" and status = ").append(sysGroup.getStatus());
            }
            if(sysGroup.getParentId()!=null){
                whereSql .append(" and parentId =").append(sysGroup.getParentId());
            }
        }
        List<SysGroup> sysGroupList = this.find(whereSql.toString(),null,null);
        return sysGroupList;
    }

    /**
     * 通过ID串，查询部门数据Map
     * @param ids 部门ID串
     * @return  Map<BigDecimal,SysGroup>
     */
    public Map<BigDecimal,SysGroup> findSysGroupMapByIds(String ids){
        List<SysGroup> sysGroupList = findSysGroupListByIds(ids);
        if(ObjectUtils.isNotEmpty(sysGroupList)){
            return sysGroupList.stream().collect(Collectors.toMap(e->e.getId(),e->e));
        }
        return null;
    }


    /**
     * 通过ID串，查询部门数据列表
     * @param ids 部门ID串
     * @return  List<SysGroup>
     */
    public List<SysGroup> findSysGroupListByIds(String ids){
        if(StringUtils.isNotEmpty(ids)){
            ids = StringUtils.subHeadTailString(ids,",");
            if(StringUtils.isNotEmpty(ids)){
                return find(" id in ("+ids+")",null,null);
            }
        }
        return null;
    }

    /**
     * 通过ID，查询部门对象
     * @param id 部门ID
     * @return SysGroup
     */
    public SysGroup findSysGroupById(BigDecimal id){
        if(ObjectUtils.isNotEmpty(id)){
            List<SysGroup> sysGroupList = this.findSysGroupListByIds(id.toString());
            if(ObjectUtils.isNotEmpty(sysGroupList)){
                return sysGroupList.get(0);
            }
        }
        return null;
    }

    /**
     * 修改部门状态
     * @param ids 部门ID串
     * @param status 状态，1正常，2禁用，3删除
     */
    public void updateSysGroupStatus(String ids,int status){
        if(StringUtils.isNotEmpty(ids)){
            ids = StringUtils.subHeadTailString(ids,",");
            if(StringUtils.isNotEmpty(ids)){
                SysGroup sysGroup = new SysGroup();
                sysGroup.setStatus(status);
                this.updateByWhereSql(sysGroup,"id in ("+ids+") or parentId in ("+ids+")");
            }
        }
    }

    /**
     * 修改部门的父级归属
     * @param id 部门ID
     * @param parentId 部门父ID
     */
    public void updateSysGroupParentId(BigDecimal id,BigDecimal parentId){
        SysGroup sysGroup = new SysGroup();
        sysGroup.setParentId(parentId);
        this.updateByWhereSql(sysGroup," id =" +id);
    }

    //====================================
    /**
     * 处理分层
     * @param sysGroupList 部门数据列表
     * @return  List<SysGroup>
     */
    private List<SysGroup> handleLayered(List<SysGroup> sysGroupList){
        if(ObjectUtils.isNotEmpty(sysGroupList)){
            Map<BigDecimal,List<SysGroup>> sysGroupListMap = sysGroupList.stream().collect(Collectors.groupingBy(e->e.getParentId()));
            //得到最顶级的部门
            List<SysGroup> parentList = sysGroupListMap.get(new BigDecimal(0));
            if(ObjectUtils.isNotEmpty(parentList)){
                parentList.forEach(e->{
                    List<SysGroup> childList = sysGroupListMap.get(e.getId());
                    if(ObjectUtils.isNotEmpty(childList)){
                        childList.forEach(em->{
                            List<SysGroup> _childList = sysGroupListMap.get(em.getId());
                            if(ObjectUtils.isNotEmpty(_childList)){
                                em.setChildSysGroupList(_childList);
                            }
                        });
                        e.setChildSysGroupList(childList);
                    }
                });
            }
            return parentList;
        }
        return sysGroupList;
    }
}
